package com.example.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.home.intent.VideoIntent
import com.example.home.model.VideoModel
import com.example.home.state.VideoState
import com.example.mvi_core.model.model.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class VideoViewModel:BaseViewModel<VideoIntent,VideoState>() {
    private val service: VideoModel by lazy{ VideoModel() }
    private val mutableState =MutableStateFlow<VideoState>(VideoState.Loading)
    val observeState:StateFlow<VideoState>
    get() = mutableState
    private val videoListState =MutableStateFlow<VideoState>(VideoState.Loading)
    val videoListObserve:StateFlow<VideoState>
        get() = videoListState
     init{
         viewModelScope.launch(Dispatchers.IO) {
             channel.consumeAsFlow().collect{
                 when(it){
                     is VideoIntent.GetVideoType->{
                         val type = service.getVideo()
                   viewModelScope.launch(Dispatchers.Main) {
                       if(type.code==0){
                           mutableState.value=VideoState.Success(type.data)
                       }else{
                           mutableState.value=VideoState.Failure(type.msg)
                       }
                   }
                     }
                     is VideoIntent.GetVideoList ->{
                         val videoList = service.getVideoList(it.id, it.page, it.size)
                         viewModelScope.launch(Dispatchers.Main) {
                             if(videoList.code==0){
                                 videoListState.value=VideoState.ListSuccess(videoList.data)
                             }else{
                                 videoListState.value=VideoState.Failure(videoList.msg)
                             }
                         }
                     }
                 }
             }
         }
     }

}